package com.dt.app.api.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dt.app.api.sys.mapper.SysDeptMapper;
import com.dt.app.api.sys.mapper.SysUserMapper;
import com.dt.app.api.sys.service.SysDeptService;
import com.dt.app.common.response.ResultUtil;
import com.dt.app.common.utils.UuidUtils;
import com.dt.app.modules.sys.entities.SysDepartmentEntity;
import com.dt.app.modules.sys.entities.SysUserEntity;
import com.dt.app.modules.sys.vo.request.SysDeptRequest;
import com.dt.app.modules.sys.vo.request.SysDeptSaveRequest;
import com.dt.app.modules.sys.vo.response.SysDeptTreeResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统部门服务实现类
 * @author DT
 * @date 2021/6/13 12:03
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDepartmentEntity> implements SysDeptService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    @Transactional(readOnly = true)
    public ResultUtil<List<SysDeptTreeResponse>> queryList(SysDeptRequest request) {
        List<SysDeptTreeResponse> entityList = this.baseMapper.queryList(request);
        if(StringUtils.isNotBlank(request.getName()) || null != request.getStartTime() || null != request.getEndTime()){
            return ResultUtil.success(entityList);
        }
        // 构建树结构数据返回
        List<SysDeptTreeResponse> treeEntityList = new ArrayList<>();
        if(null != entityList && !entityList.isEmpty()){
            treeEntityList =  buildTree(entityList,"0");
        }
        return ResultUtil.success(treeEntityList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil<SysDeptSaveRequest> saveDept(SysDeptSaveRequest request) {
        SysDepartmentEntity entity = new SysDepartmentEntity();
        BeanUtils.copyProperties(request,entity);
        entity.setId(UuidUtils.getUniqueIdByUUId());
        int insert = this.baseMapper.insert(entity);
        return insert > 0 ? ResultUtil.success(request) : ResultUtil.error();
    }

    @Override
    @Transactional(readOnly = true)
    public ResultUtil<SysDepartmentEntity> getDeptById(String id) {
        SysDepartmentEntity entity = this.baseMapper.selectById(id);
        return ResultUtil.success(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil<SysDeptSaveRequest> updateDept(SysDeptSaveRequest request) {
        SysDepartmentEntity entity = new SysDepartmentEntity();
        BeanUtils.copyProperties(request,entity);
        int update = this.baseMapper.updateById(entity);
        return update > 0 ? ResultUtil.success(request) : ResultUtil.error();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil<SysDepartmentEntity> deleteDept(String id) {
        Integer selectCount = this.baseMapper.selectCount(new QueryWrapper<SysDepartmentEntity>().eq("pid", id));
        if(null != selectCount && selectCount > 0){
            return ResultUtil.error("请先删除子节点！");
        }
        Integer count = sysUserMapper.selectCount(new QueryWrapper<SysUserEntity>().eq("dept_id", id));
        if(null != count && count > 0){
            return ResultUtil.error("该节点已有用户使用！");
        }
        int delete = this.baseMapper.deleteById(id);
        return delete > 0 ? ResultUtil.success() : ResultUtil.error();
    }

    @Override
    @Transactional(readOnly = true)
    public ResultUtil<List<SysDeptTreeResponse>> listTree(Integer type) {
        List<SysDeptTreeResponse> entityList = new ArrayList<>();
        List<SysDepartmentEntity> sysDepartmentEntityList = this.baseMapper.selectList(null);
        if(!sysDepartmentEntityList.isEmpty()) {
            sysDepartmentEntityList.forEach(it -> {
                SysDeptTreeResponse response = new SysDeptTreeResponse();
                BeanUtil.copyProperties(it,response);
                entityList.add(response);
            });
        }
        // 构建树结构数据返回
        List<SysDeptTreeResponse> treeEntityList = new ArrayList<>();
        if(!entityList.isEmpty()) {
            treeEntityList =  buildTree(entityList, "0");
        }
        if(type == 1) {
            // 添加顶级节点
            SysDeptTreeResponse response = new SysDeptTreeResponse();
            response.setId("0");
            response.setPid("-1");
            response.setOrderNum(0);
            response.setName("DTBoot管理系统");
            treeEntityList.add(response);
        }
        // 排序输出
        return ResultUtil.success(treeEntityList.stream().sorted(Comparator.comparing(SysDeptTreeResponse::getOrderNum)).collect(Collectors.toList()));
    }

    public static List<SysDeptTreeResponse> buildTree(List<SysDeptTreeResponse> list, String pid){
        List<SysDeptTreeResponse> children = list.stream().filter(x -> x.getPid().equals(pid)).collect(Collectors.toList());
        List<SysDeptTreeResponse> subclass = list.stream().filter(x -> !x.getPid().equals(pid)).collect(Collectors.toList());
        if(children.size() > 0){
            children.forEach(x -> {
                if(subclass.size() > 0){
                    buildTree(subclass,x.getId()).forEach(
                            y -> x.getChildren().add(y)
                    );
                }
            });
        }
        return children;
    }

}
